package io.gitee.chearnee.fw.socket.component;

import io.gitee.chearnee.fw.socket.component.channelHandler.DispatcherChannelHandler;
import io.gitee.chearnee.fw.socket.component.channelHandler.TextWebSocketFrameHandler;
import io.gitee.chearnee.fw.socket.component.codec.NettyMessageDecode;
import io.gitee.chearnee.fw.socket.component.codec.NettyMessageEncode;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) {
        socketChannel.pipeline()
                .addLast(new HttpServerCodec())
                .addLast(new ChunkedWriteHandler())
                .addLast(new HttpObjectAggregator(8192))
                .addLast(new WebSocketServerProtocolHandler("/ws"))
                .addLast(new LineBasedFrameDecoder(1024))
                .addLast(new IdleStateHandler(0, 5 * 60, 0, TimeUnit.SECONDS))
                .addLast(new TextWebSocketFrameHandler())
                .addLast(new StringEncoder())
                .addLast(new StringDecoder())
//                //自定义编码解码器
                .addLast(new NettyMessageDecode())
                .addLast(new NettyMessageEncode())
//                //加心跳触发器
                .addLast(new ServerIdleStateTrigger())
//                //自定义处理器
                .addLast(new DispatcherChannelHandler());

    }
}
